using SqlSugar;
using SqlsugarService.Application.Service;
using SqlsugarService.Infrastructure.IRepository;
using SqlsugarService.Infrastructure.Repository;
using SqlsugarService.Infrastructure.DbContext;
using SqlsugarService.Application.IService;
using SqlsugarService.Application.IService.Sales;
using SqlsugarService.Application.Service.Sales;
using SqlsugarService.API;
using SqlsugarService.Application.IService.Material;
using SqlsugarService.Application.Service.Material;
using SqlsugarService.Application.IService.Process.ProcessComposition;
using SqlsugarService.Application.Service.Process.ProcessComposition;
using SqlsugarService.Application.IService.Plan;
using SqlsugarService.Application.Service.Plan;
using SqlsugarService.Application.IService.Process.BomManagement;
using SqlsugarService.Application.Service.Process.BomManagement;
using SqlsugarService.Application.IService.ProductionOrders;
using SqlsugarService.Application.Service.ProductionOrders;
using SqlsugarService.Application.AI.KouZi_AI;
using SqlsugarService.Application.AI.LangChain;
using SqlsugarService.Application.AI.MES;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "SqlsugarService API",
        Version = "v1",
        Description = "基于 SqlSugar 的数据服务微服务 - 提供数据访问和业务逻辑处理"
    });

    // 包含 XML 注释
    var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
    }

    // 确保包含所有控制器
    c.DocInclusionPredicate((name, api) => true);
});

// 配置 HttpClient for KouziAI
builder.Services.AddHttpClient("KouZiAI", (serviceProvider, client) =>
{
    var configuration = serviceProvider.GetRequiredService<IConfiguration>();

    // 从配置文件读取设置
    var apiBaseUrl = configuration["KouZiAI:ApiBaseUrl"] ?? "https://api.coze.cn";
    var apiToken = configuration["KouZiAI:ApiToken"];
    var timeoutMinutes = configuration.GetValue<int>("KouZiAI:TimeoutMinutes", 5);

    client.BaseAddress = new Uri(apiBaseUrl);

    // 如果配置了API Token，则添加认证头
    if (!string.IsNullOrEmpty(apiToken) && apiToken != "YOUR_API_TOKEN_HERE")
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiToken}");
    }
    else
    {
        // 记录配置警告
        var logger = serviceProvider.GetService<ILogger<Program>>();
        logger?.LogWarning("KouZiAI API Token 未正确配置，请检查 appsettings.json 中的 KouZiAI:ApiToken 配置");
    }

    client.Timeout = TimeSpan.FromMinutes(timeoutMinutes);

    // 设置其他默认头部
    client.DefaultRequestHeaders.Add("User-Agent", "SqlsugarService/1.0");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

// 注意：不再需要为 Semantic Kernel 配置 HttpClient，它有自己的 HTTP 处理机制

builder.Services.AddScoped<SqlSugarDbContext>();
// 关键：注册ISqlSugarClient，从SqlSugarDbContext中获取实例
builder.Services.AddScoped<ISqlSugarClient>(provider =>
{
    return provider.GetRequiredService<SqlSugarDbContext>().Db;
});
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

// 注册数据库初始化服务
builder.Services.AddScoped<SqlsugarService.Infrastructure.Services.DatabaseInitializationService>();

builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<ISalesService, SalesService>();
builder.Services.AddScoped<IProductEntityService, ProductEntityService>();
builder.Services.AddScoped<IProductionPlanService, ProductionPlanService>();
builder.Services.AddScoped<IBomService, BomService>();
builder.Services.AddScoped<IProductionOrderService, ProductionOrderService>();
builder.Services.AddScoped<IBomDecompositionService, BomDecompositionService>();
builder.Services.AddScoped<IWorkOrderTaskService, WorkOrderTaskService>();

// 注册 LMZ 排工系统服务
builder.Services.AddScoped<SqlsugarService.Application.IService.LMZWorkSchedule.ILMZWorkScheduleService, SqlsugarService.Application.Service.LMZWorkSchedule.LMZWorkScheduleService>();


builder.Services.AddAutoMapper(x =>
{
    x.AddProfile(new Mapperfiles());
});
// 注册物料服务
builder.Services.AddScoped<IMaterialService, MaterialService>();
builder.Services.AddScoped<IProcessCompositionService, ProcessCompositionService>();

// 注册 KouziAI 服务
builder.Services.AddScoped<IKouZiAIService, KouZiAIService>();

// 注册 Semantic Kernel 服务 (原 LangChain 服务，现已迁移到 Microsoft Semantic Kernel)
builder.Services.AddScoped<ILangChainService, LangChainService>();

// 注册 MES 工具服务
builder.Services.AddScoped<IMESToolService, MESToolService>();

// 注册 MES 知识库服务
builder.Services.AddScoped<IMESKnowledgeService, MESKnowledgeService>();

// 注册 MES 专用 LangChain 服务
builder.Services.AddScoped<IMESLangChainService, MESLangChainService>();

// 注册质检相关服务
builder.Services.AddScoped<SqlsugarService.Application.Service.QualityInspection.QualityInspectionPlanWorkReportService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
// 启用 Swagger 在所有环境（包括生产环境）
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "SqlsugarService API v1");
    c.RoutePrefix = "swagger"; // Swagger UI 在 /swagger 路径

    // 优化显示
    c.DefaultModelsExpandDepth(-1);
    c.DefaultModelExpandDepth(2);
    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
    c.DisplayRequestDuration();
    c.EnableDeepLinking();

    // 自定义样式
    c.DocumentTitle = "SqlsugarService API 文档";
});
app.UseStaticFiles();
app.UseAuthorization();

app.MapControllers();

// 添加根路径重定向到 Swagger (所有环境)
app.MapGet("/", () => Results.Redirect("/swagger")).ExcludeFromDescription();

// 添加健康检查端点
app.MapGet("/health", () => Results.Ok(new
{
    status = "healthy",
    timestamp = DateTime.UtcNow,
    version = "1.0.0",
    environment = app.Environment.EnvironmentName
})).ExcludeFromDescription();

app.Run();

